package com.fivestar.pmanager.web.controller;

import static com.fivestar.pmanager.core.util.LoggerHelper.logError;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fivestar.pmanager.constants.CommonConstants;
import com.fivestar.pmanager.core.base.AjaxRespBean;
import com.fivestar.pmanager.core.base.PageBean;
import com.fivestar.pmanager.core.exception.DMLNoRecordEffectedException;
import com.fivestar.pmanager.core.util.MD5Util;
import com.fivestar.pmanager.model.FsUserBean;
import com.fivestar.pmanager.model.SysRoleBean;
import com.fivestar.pmanager.model.SysRoleUserBean;
import com.fivestar.pmanager.service.FsUserService;
import com.fivestar.pmanager.service.SysRoleService;
import com.fivestar.pmanager.service.SysRoleUserService;
import com.fivestar.pmanager.web.business.service.FsUserBusiService;
import com.fivestar.pmanager.web.business.service.SysRoleUserBusiService;

/**
 * 系统用户控制器
 *
 * Created by admin 
 */
@Controller("fsUserController")
@RequestMapping("user/fsUser")
public class FsUserController extends BaseController implements CommonConstants
{
	private static final Logger logger = LoggerFactory.getLogger(FsUserController.class);
	@Autowired
    private FsUserService fsUserService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleUserBusiService sysRoleUserBusiService;
	@Autowired
	private SysRoleUserService sysRoleUserService;
	@Autowired
	private FsUserBusiService fsUserBusiService;

	
	/**
	 * 初始化列表页面
	 */
	@RequestMapping("initQuery")
    public ModelAndView initQuery(FsUserBean searchParam, PageBean pageBean, HttpServletRequest request)
    {
        if(isKeepSearchParameter())
        {
            getSearchParamFromSession(searchParam, pageBean);
        }
        else
        {
            searchParam.setSortBy(FsUserBean.SORT_BY_DESC);
            searchParam.setSortField("create_time");
        }
        List<SysRoleBean> roleList = sysRoleService.getList(new SysRoleBean());
        request.setAttribute("roleList", roleList);
        return new ModelAndView("user/fsUserList").
        		addObject("searchParam", searchParam).
        		addObject("pageBean", pageBean);
    }


    /**
     * 分页查询
     * @param searchParam
     * @param pageBean
     * @return
     */
    @RequestMapping("query")
    @ResponseBody
    public PageBean query(FsUserBean searchParam, PageBean pageBean)
    {
        setSearchParamToSession(searchParam, pageBean);
        searchParam.setSortBy(FsUserBean.SORT_BY_DESC);
        searchParam.setSortField("create_time");
        //默认条件
        fsUserService.page(searchParam, pageBean);
        return pageBean;
    }


    /**
     * 分页查询(全部)
     * @param searchParam
     * @param pageBean
     * @return
     */
    @RequestMapping("queryUser")
    @ResponseBody
    public PageBean queryUser(FsUserBean searchParam, PageBean pageBean)
    {
        setSearchParamToSession(searchParam, pageBean);
        //默认条件
        fsUserService.page(searchParam, pageBean);
        return pageBean;
    }
    
    /**
     * 初始化新增页面
     * @return
     */
    @RequestMapping("initAdd")
    public ModelAndView initAdd()
    {
    	
        return new ModelAndView("user/addFsUser");
    }
    
    /**
     * 新增
     * @param fsUser
     * @return
     */
    @RequestMapping("add")
    public @ResponseBody AjaxRespBean add(FsUserBean fsUser)
    {
        AjaxRespBean ajaxRespBean;
        try
        {
        	// 设置初始用户状态 
        	fsUser.setStatus(USER_STATE_0);
        	fsUser.setPassword(MD5Util.MD5(fsUser.getPassword()));
        	fsUserBusiService.addUser(fsUser, getCommonParameter());
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("add.success"));
        }
        catch (DMLNoRecordEffectedException e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("add.fail"));
        }
        catch (Exception e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.failResp(getMessage("add.fail.reason") + e.getMessage());
        }
        return ajaxRespBean;
    }
    
    /**
     * 启用
     * @param fsUser
     * @return
     */
    @RequestMapping("enable")
    public @ResponseBody AjaxRespBean enable(FsUserBean fsUser)
    {
    	AjaxRespBean ajaxRespBean;
    	try
    	{
    		fsUser.setStatus(USER_STATE_0);
    		fsUserBusiService.updateUserStatus(fsUser, getCommonParameter());
    		ajaxRespBean = AjaxRespBean.successResp(null, getMessage("edit.success"));
    	}
    	catch (DMLNoRecordEffectedException e)
    	{
    		logError(logger, e);
    		ajaxRespBean = AjaxRespBean.successResp(null, getMessage("edit.fail"));
    	}
    	catch (Exception e)
    	{
    		logError(logger, e);
    		ajaxRespBean = AjaxRespBean.failResp(getMessage("edit.fail.reason") + e.getMessage());
    	}
    	return ajaxRespBean;
    }
    
    /**
     * 禁用
     * @param fsUser
     * @return
     */
    @RequestMapping("disable")
    public @ResponseBody AjaxRespBean disable(FsUserBean fsUser)
    {
    	AjaxRespBean ajaxRespBean;
    	try
    	{
    		fsUser.setStatus(USER_STATE_1);
    		fsUserBusiService.updateUserStatus(fsUser, getCommonParameter());
    		ajaxRespBean = AjaxRespBean.successResp(null, getMessage("edit.success"));
    	}
    	catch (DMLNoRecordEffectedException e)
    	{
    		logError(logger, e);
    		ajaxRespBean = AjaxRespBean.successResp(null, getMessage("edit.fail"));
    	}
    	catch (Exception e)
    	{
    		logError(logger, e);
    		ajaxRespBean = AjaxRespBean.failResp(getMessage("edit.fail.reason") + e.getMessage());
    	}
    	return ajaxRespBean;
    }
    
    /**
     * 新增用户角色
     * @param userId
     * @param roleIds
     * @return
     */
    @RequestMapping("addUserRole")
    public @ResponseBody AjaxRespBean addUserRole(int userId,String roleIds)
    {
        AjaxRespBean ajaxRespBean;
        try
        {
        	sysRoleUserBusiService.addUserRole(userId, roleIds, getCommonParameter());
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("add.success"));
        }
        catch (DMLNoRecordEffectedException e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("add.success"));
        }
        catch (Exception e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.failResp(getMessage("add.fail.reason") + e.getMessage());
        }
        return ajaxRespBean;
    }
    
    /**
     * 新增用户角色
     * @param roleId
     * @return
     */
    @RequestMapping("addUserRole2")
    public @ResponseBody AjaxRespBean addUserRole2(int roleId,String userIds)
    {
        AjaxRespBean ajaxRespBean;
        try
        {
        	sysRoleUserBusiService.addUserRole2(roleId, userIds, getCommonParameter());
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("add.success"));
        }
        catch (DMLNoRecordEffectedException e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("add.success"));
        }
        catch (Exception e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.failResp(getMessage("add.fail.reason") + e.getMessage());
        }
        return ajaxRespBean;
    }
    
    /**
     * 查询用户角色
     * @param userId
     * @return
     */
    @RequestMapping("queryUserRole")
    public @ResponseBody String queryUserRole(int userId)
    {
        String roleIds = "";
        SysRoleUserBean roleUser = new SysRoleUserBean();
        roleUser.setUserId(userId);
        List<SysRoleUserBean> userRoleList = sysRoleUserService.getList(roleUser);
        for (int i=0; i<userRoleList.size(); i++) {
        	String septor = (i == userRoleList.size() -1) ? "" : ",";
        	roleIds += userRoleList.get(i).getRoleId()+ septor;
		}
        return roleIds;
    }
    
    /**
     * 删除角色
     */
    @RequestMapping("delete")
    public @ResponseBody AjaxRespBean delete(int rowId)
    {
        AjaxRespBean ajaxRespBean;
        try
        {
            sysRoleUserBusiService.deleteUser(rowId, getCommonParameter());

            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("delete.success"));
        }
        catch (DMLNoRecordEffectedException e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("delete.fail"));
        }
        catch (Exception e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.failResp(
            		getMessage("delete.fail.reason") + e.getMessage());
        }
        return ajaxRespBean;
    }
    
    /**
     * 批量删除
     * @param rowIds
     * @return
     */
    @RequestMapping("deleteBatch")
    public @ResponseBody AjaxRespBean deleteBatch(String rowIds)
    {
        AjaxRespBean ajaxRespBean;
        try
        {
        	sysRoleUserBusiService.deleteBatchUser(rowIds, getCommonParameter());
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("delete.success"));
        }
        catch (DMLNoRecordEffectedException e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("delete.fail"));
        }
        catch (Exception e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.failResp(
            		getMessage("delete.fail.reason") + e.getMessage());
        }
        return ajaxRespBean;
    }
    
    /**
     * 初始化修改页面
     * @param rowId
     * @return
     */
    @RequestMapping("initEdit")
    public ModelAndView initEdit(int rowId)
    {
    	FsUserBean temp = new FsUserBean();
        temp.setRowId(rowId);
        return new ModelAndView("user/editFsUser");
    }
    
    /**
     * 修改
     * @param mdUser
     * @return
     */
    @RequestMapping("edit")
    public @ResponseBody AjaxRespBean edit(FsUserBean fsUser)
    {
        AjaxRespBean ajaxRespBean;
        try
        {
        	fsUserService.updateBySelective(fsUser,getCommonParameter());
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("edit.success"));
        }
        catch (DMLNoRecordEffectedException e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("edit.success"));
        }
        catch (Exception e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.failResp(getMessage("edit.fail.reason") + e.getMessage());
        }
        return ajaxRespBean;
    }
    
    /**
     * 验证手机号是否唯一
     * @param phone
     * @return true：唯一  false:不唯一
     */
    @RequestMapping("checkPhoneUnique")
    public @ResponseBody Boolean checkPhoneUnique(String phone)
    {
        FsUserBean FsUserBean = fsUserService.getByPhone(phone);
        return null == FsUserBean;
    }

    /**
     * 验证用户名是否唯一
     * @param name
     * @return true：唯一  false:不唯一
     */
    @RequestMapping("checkNameUnique")
    public @ResponseBody Boolean checkNameUnique(String name)
    {
        FsUserBean FsUserBean = fsUserService.getByName(name);
        return null == FsUserBean;
    }

    /**
     * 重置密码
     * @param mdUser
     * @return
     */
    @RequestMapping("resetPwd")
    public @ResponseBody AjaxRespBean resetPwd(FsUserBean fsUser)
    {
        AjaxRespBean ajaxRespBean;
        try
        {
        	fsUser.setPassword(MD5Util.string2MD5(fsUser.getPassword()).toLowerCase());
        	fsUserService.updateBySelective(fsUser, getCommonParameter());
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("reset.pwd.success"));
        }
        catch (DMLNoRecordEffectedException e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.successResp(null, getMessage("reset.pwd.success"));
        }
        catch (Exception e)
        {
            logError(logger, e);
            ajaxRespBean = AjaxRespBean.failResp(getMessage("reset.pwd.fail.exception") + e.getMessage());
        }
        return ajaxRespBean;
    }



    /**
     * 个人信息页面
     * @param rowId
     * @return
     */
    @RequestMapping("mineInfo")
    public ModelAndView mineInfo(Integer rowId)
    {	
    	FsUserBean fsUser = fsUserService.getSingleByParam(rowId);
    	return new ModelAndView("user/mineInfo").
    			addObject("fsUser",fsUser);
    }


    /**
     * 初始化 查看 页面
     * @param rowId
     * @return
     */
    @RequestMapping("view")
    public ModelAndView view(int rowId)
    {
        return new ModelAndView("user/userDetails").addObject("fsUser", fsUserService.getSingleByParam(rowId));
    }

}
